package com.example.demo.controller;

import com.example.demo.service.LoginaService;
import com.example.demo.service.UserService;
import com.example.demo.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@ComponentScan
public class GetPasswordController {
    @Autowired
    private MailUtil mailUtil ;
    @Autowired
    UserService userService;
    @Autowired
    private LoginaService loginaService;

    /**
     * 找回密码功能如下
     * @return
     */
    @RequestMapping("/getPassword")
    public String loginYemian() {
        return "getPassword";
    }
    @RequestMapping("/getPassword-form")
    public ModelAndView getPassword(String username, String email, String codeInput, HttpSession session) {
        String codeEmail = (String) session.getAttribute("codeEmail");
        //判断验证码
        if (loginaService.checkCode(codeEmail, codeInput)) {
            String password = userService.getPasswordByusername(username);
            mailUtil.sendPassword(email,username,password);
            return new ModelAndView("redirect:/getpasswordsuccess");
        }else {
            return new ModelAndView("redirect:/getpasswordfalse-code");
        }
    }

    @RequestMapping("/getpasswordsuccess")
    @ResponseBody
    public String getpasswordsuccess() {
        return "<script type='text/javascript'>alert('密码已经发送到您的邮箱，请进行登录');window.location='/login'</script>";
    }

    @RequestMapping("/getpasswordfalse-code")
    @ResponseBody
    public String getpasswordfalsecode() {
        return "<script type='text/javascript'>alert('验证码输入错误，请重新输入');window.location='/getPassword'</script>";
    }



    @RequestMapping("/getPasswordCodeEmail")
    @ResponseBody
    public int getCheckCode(String username ,String email, HttpSession session) {
        if (userService.checkUsernameAndEmail(username, email)) {
            //核对信息
            String codeEmail = mailUtil.getCheckCode(email);
            System.out.println("发送到：" + email + "的验证码为：" + codeEmail);
            session.setAttribute("codeEmail", codeEmail);
            session.setAttribute("email", email);
            int flag = 200;
            return flag;
        }else {
            int flag = 500;
            return flag;
        }
    }
}
